package com.dss.auto_deploy.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dss.auto_deploy.config.DssProperties;
import com.dss.auto_deploy.domain.AdmDockerDeploy;
import com.dss.auto_deploy.event.DockerPullAndStartEvent;
import com.dss.auto_deploy.service.IAdmDockerDeployService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;

/**
 * @Description:
 * @author: dongshoushan
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class DockerPullAndStartListener {
    private final IAdmDockerDeployService admDockerDeployService;
    private final DssProperties dssProperties;

    @Async
    @Order
    @EventListener(DockerPullAndStartEvent.class)
    public void run(DockerPullAndStartEvent event) {
        AdmDockerDeploy admDockerDeploy = event.getAdmDockerDeploy();
        String imageName = event.getImageName();
        List<AdmDockerDeploy> list = admDockerDeployService.list(Wrappers.lambdaQuery(AdmDockerDeploy.class).eq(AdmDockerDeploy::getProjectId, admDockerDeploy.getProjectId())
                .eq(AdmDockerDeploy::getNamespaceId, admDockerDeploy.getNamespaceId())
                .eq(AdmDockerDeploy::getEnable, 0)
                .eq(AdmDockerDeploy::getModuleName, admDockerDeploy.getModuleName()));
        for (int i = 0; i < list.size(); i++) {
            AdmDockerDeploy dockerDeploy = list.get(i);
            try {
                Random random = new Random();
                int sleepTime = random.nextInt(5); // 生成0到3之间的随机整数
                Thread.sleep(sleepTime * 1000L);
//                log.info("deploy_pull_queue队列收到消息 dockerID:{}开始执行pull：{}并启动新容器", dockerDeploy.getDockerId(), imageName);
                admDockerDeployService.pullAndStart(dockerDeploy, imageName);
                admDockerDeployService.reloadHtml();
                if (i < list.size()-1){
                    Thread.sleep(dssProperties.getRestartInterval());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
